<template>
  <div class="wrong-exercise-container">
    <h2 class="mb-4">
      错题本
    </h2>
    
    <!-- 新增：题目类型筛选 -->
    <div class="filter-section mb-4">
      <label>筛选类型：</label>
      <select
        v-model="filterType"
        class="filter-dropdown"
      >
        <option value="">
          全部
        </option>
        <option value="0">
          选择题
        </option>
        <option value="1">
          主观题
        </option>
      </select>
    </div>

    <!-- 使用筛选后的题目列表 -->
    <QuestionCard
      title="我的错题" 
      :questions="filteredQuestions" 
    />

    <!-- 加载状态和错误提示 -->
    <!-- <div v-if="loading" class="loading">加载中...</div> -->
    <div
      v-if="error"
      class="error"
    >
      {{ error }}
    </div>
  </div>
</template>

<script>
import QuestionCard from './QuestionCard.vue';
import axios from 'axios';

export default {
  components: { QuestionCard },
  props: {
    userId: {
      type: String,
      required: true
    },
    courseId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      wrongQuestions: [],        // 原始错题列表（未筛选）
      filterType: '',            // 筛选类型（空: 全部，0: 选择题，1: 主观题）
      loading: true,             // 加载状态
      error: null                // 错误信息
    };
  },
  computed: {
    // 计算属性：根据类型筛选题目
    filteredQuestions() {
      if (!this.filterType) return this.wrongQuestions;  // 未选择筛选时返回全部
      return this.wrongQuestions.filter(question => 
        question.type === Number(this.filterType)  // 按题目类型过滤
      );
    }
  },
  mounted() {
    this.fetchWrongQuestions();
  },
  methods: {
    async fetchWrongQuestions() {
    this.loading = true;
    this.error = null;
  
  try {
    const userId = this.userId;
    const courseId = this.courseId  ;

    const response = await axios.get('/api/exercises/wrong', {
      params: { userId, courseId }
    });

    if (response.data && Array.isArray(response.data)) {
      // 直接使用 response.data 作为题目列表
      this.wrongQuestions = response.data.map(question => ({
        id: question.questionId,
        questionName: question.questionName || '',
        type: question.type === false ? 0 : 1,
        content: question.questionContent,
        score: question.questionScore,
        answer: question.questionAnswer,
        options: []
      }));

      // 处理选择题选项
      // 处理选择题选项
      this.wrongQuestions = this.wrongQuestions.map(q => {
        if (q.type === 0 && q.content) {
          const lines = q.content.split('\n').map(line => line.trim());
          
          // 提取选项（A.、B.、C.、D.）
          const options = lines
            .filter(line => /^[A-D]\./i.test(line))  // 匹配 A. B. C. D.
            .map(line => line.replace(/^[A-D]\.\s*/i, '').trim()); // 去除前缀

          q.options = options.length > 0 ? options : ['选项A', '选项B', '选项C', '选项D'];
          q.stem = lines[0]; // 将第一行作为题干
        }
        return q;
      });

    } else {
      this.wrongQuestions = [];
      this.error = '后端返回的错题数据为空或格式不正确';
      console.error('无效的数据结构:', response.data);
    }

  } catch (error) {
    if (error.response) {
      console.error('服务器错误:', error.response.data);
    }
  }
}}};
</script>

<style scoped>
.wrong-exercise-container {
  padding: 2rem;
}

/* 新增：筛选区域样式（与收藏题目页面保持一致） */
.filter-section {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.filter-dropdown {
  padding: 0.4rem 0.8rem;
  border: 1px solid #e4e7eb;
  border-radius: 4px;
  font-size: 0.9rem;
}

.loading, .error {
  margin-top: 1rem;
  padding: 0.5rem;
  color: #6c757d;  /* 统一文字颜色 */
}

.error {
  color: #ff4d4f;  /* 错误信息红色 */
}
</style>
